package com.aiti.lulian.service.newCard;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.lulian.dto.newCard.CardEnterpriseCooperationAddParamDto;
import com.aiti.lulian.dto.newCard.EnterpriseCooperationQueryDto;
import com.aiti.lulian.dto.newCard.UpdateWechatGroupParamDto;
import com.aiti.lulian.entity.CardEnterpriseCircleUserCard;
import com.aiti.lulian.entity.newCard.CardEnterpriseCooperation;
import com.aiti.lulian.mapper.newCard.CardEnterpriseCooperationMapper;
import com.aiti.lulian.mapper.newCard.CardPersonalBaseInfoMapper;
import com.aiti.lulian.vo.newCard.CardEnterpriseCooperationVo;
import com.aiti.lulian.vo.newCard.CircleAdminVo;
import com.aiti.lulian.vo.newCard.CooperationEnterpriseVo;
import com.aiti.lulian.vo.newCard.inviterRankVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

/**
 * description:
 * auth fcb
 * date 2025-08-20 14:30
 **/
@Service
@Slf4j
public class CardEnterpriseCooperationService extends BaseSerivceImpl<CardEnterpriseCooperationMapper, CardEnterpriseCooperation> {

    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;

    /**
     * 查询企业名片的id和名称
     * @param enterpriseCardId
     * @return
     */
    public CooperationEnterpriseVo getEnterpriseInfoByEnterpriseCardId(String enterpriseCardId) {
        if(StrUtil.isBlank(enterpriseCardId)) {
            throw new BusinessException("参数错误");
        }
        CooperationEnterpriseVo cooperationEnterpriseVo = cardPersonalBaseInfoMapper.queryCooperationEnterprise(enterpriseCardId);
        if(cooperationEnterpriseVo == null) {
            throw new BusinessException("名片不存在");
        }
        return cooperationEnterpriseVo;
    }

    /**
     * 发布一条合作信息
     * @param paramDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void addEnterpriseCooperation(CardEnterpriseCooperationAddParamDto paramDto) {
        this.checkAddParam(paramDto);
        CardEnterpriseCircleUserCard cardEnterpriseCircleUserCard = this.baseMapper.queryCircleAdminInfo(paramDto.getCircleId(), paramDto.getEnterpriseCardId());
        if(cardEnterpriseCircleUserCard == null) {
            throw new BusinessException("请先申请加入该名企圈");
        }
        // 这里先不考虑去重的情况，目前不清楚是否允许重复
        CardEnterpriseCooperation cooperationEnterprise = this.buildCooperationEnterprise(paramDto);
        this.save(cooperationEnterprise);
    }

    /**
     * 查询合作信息列表
     * @param queryDto
     * @return
     */
    public PageResult<CardEnterpriseCooperationVo> queryEnterpriseCooperationList(EnterpriseCooperationQueryDto queryDto) {
        IPage<CardEnterpriseCooperationVo> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<CardEnterpriseCooperationVo> list = this.baseMapper.queryEnterpriseCooperationList(page, queryDto);
        if(CollectionUtil.isNotEmpty( list)) {
            LocalDate today = LocalDate.now();
            for(CardEnterpriseCooperationVo vo : list) {
                // 设置剩余时间
                LocalDate endDate = LocalDate.parse(vo.getEndTime());
                long remainTime = ChronoUnit.DAYS.between(today, endDate);
                if(remainTime < 0) {
                    remainTime = 0;
                }
                vo.setRemainTime(remainTime);
            }
        }
        PageResult<CardEnterpriseCooperationVo> pageResult = new PageResult<>(list, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    /**
     * 查询合作详情
     * @param enterpriseCooperationId
     * @return
     */
    public CardEnterpriseCooperationVo getEnterpriseCooperationById(String enterpriseCooperationId) {
        if(StrUtil.isBlank(enterpriseCooperationId)) {
            throw new BusinessException("参数错误");
        }
        return this.baseMapper.getEnterpriseInfoById(enterpriseCooperationId);
    }

    /**
     * 查询邀请人排行
     * @param circleId
     * @return
     */
    public List<inviterRankVo> queryInviterRankList(String circleId) {
        return this.baseMapper.queryInviterRankList(circleId);
    }

    /**
     * 查询当前人员在当前圈子的地位
     * @param circleId
     * @param enterpriseCardId
     * @return
     */
    public CircleAdminVo queryCircleAdminInfo(String circleId, String enterpriseCardId) {
        CardEnterpriseCircleUserCard cardEnterpriseCircleUserCard = this.baseMapper.queryCircleAdminInfo(circleId, enterpriseCardId);
        CircleAdminVo circleAdminVo = new CircleAdminVo();
        if(cardEnterpriseCircleUserCard == null) {
            circleAdminVo.setInCircle(false);
            circleAdminVo.setIsAdmin(false);
            circleAdminVo.setIsManager(false);
            return circleAdminVo;
        }else {
            if("2".equals(cardEnterpriseCircleUserCard.getType())) {
                circleAdminVo.setInCircle(true);
                circleAdminVo.setIsAdmin(true);
                circleAdminVo.setIsManager(false);
            }
            if("1".equals(cardEnterpriseCircleUserCard.getType())) {
                circleAdminVo.setInCircle(true);
                circleAdminVo.setIsAdmin(false);
                circleAdminVo.setIsManager(true);
            }
            if("0".equals(cardEnterpriseCircleUserCard.getType())) {
                circleAdminVo.setInCircle(true);
                circleAdminVo.setIsAdmin(false);
                circleAdminVo.setIsManager(false);
            }
        }
        if(circleAdminVo.getInCircle()) {
            String groupUrl = this.baseMapper.queryCircleWeChatGroupUrl(circleId);
            circleAdminVo.setWechatGroupUrl(groupUrl);
        }
        return circleAdminVo;
    }

    /**
     * 修改圈子微信群二维码
     * @param paramDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCircleWechatGroupUrl(UpdateWechatGroupParamDto paramDto) {
        if(StrUtil.isBlank(paramDto.getCircleId())) {
            throw new BusinessException("参数错误");
        }
        if(StrUtil.isBlank(paramDto.getWechatGroupUrl())) {
            paramDto.setWechatGroupUrl(null);
        }
        this.baseMapper.updateCircleWechatGroupUrl(paramDto);
    }

    private CardEnterpriseCooperation buildCooperationEnterprise(CardEnterpriseCooperationAddParamDto paramDto) {
        CardEnterpriseCooperation cooperationEnterprise = new CardEnterpriseCooperation();
        Date now = new Date();
        cooperationEnterprise.setBaseId(IdUtil.simpleUUID());
        cooperationEnterprise.setCircleId(paramDto.getCircleId());
        cooperationEnterprise.setRequirementType(paramDto.getRequirementType());
        cooperationEnterprise.setRequirementTitle(paramDto.getRequirementTitle());
        cooperationEnterprise.setProcurementAmount(paramDto.getProcurementAmount());
        cooperationEnterprise.setProcurementUnit(paramDto.getProcurementUnit());
        cooperationEnterprise.setEndTime(DateUtil.parse(paramDto.getEndTime()));
        cooperationEnterprise.setEnterpriseId(paramDto.getEnterpriseId());
        cooperationEnterprise.setEnterpriseName(paramDto.getEnterpriseName());
        cooperationEnterprise.setLinkMan(paramDto.getLinkMan());
        cooperationEnterprise.setLinkPhone(paramDto.getLinkPhone());
        cooperationEnterprise.setBaseCreateBy(paramDto.getUserId());
        cooperationEnterprise.setBaseCreateCardId(paramDto.getEnterpriseCardId());
        cooperationEnterprise.setBaseCreateTime(now);
        cooperationEnterprise.setBaseUpdateBy(paramDto.getUserId());
        cooperationEnterprise.setBaseUpdateTime(now);
        cooperationEnterprise.setIsDelete(0);
        return cooperationEnterprise;
    }

    private void checkAddParam(CardEnterpriseCooperationAddParamDto paramDto) {
//        if(StrUtil.isBlank(paramDto.getUserId())) {
//            throw new BusinessException("参数错误");
//        }
        if(StrUtil.isBlank(paramDto.getEnterpriseCardId())) {
            throw new BusinessException("参数错误");
        }
        if(StrUtil.isBlank(paramDto.getCircleId())) {
            throw new BusinessException("名企圈标识不能为空");
        }
        if(StrUtil.isBlank(paramDto.getRequirementType())) {
            throw new BusinessException("需求类型不能为空");
        }
        if(StrUtil.isBlank(paramDto.getRequirementTitle())) {
            throw new BusinessException("需求标题不能为空");
        }
        if(StrUtil.isBlank(paramDto.getProcurementAmount())) {
            throw new BusinessException("采购量不能为空");
        }
        if(StrUtil.isBlank(paramDto.getProcurementUnit())) {
            throw new BusinessException("采购单位不能为空");
        }
        if(StrUtil.isBlank(paramDto.getEndTime())) {
            throw new BusinessException("截至时间不能为空");
        }
        if(StrUtil.isBlank(paramDto.getEnterpriseId())) {
            throw new BusinessException("企业id不能为空");
        }
        if(StrUtil.isBlank(paramDto.getEnterpriseName())) {
            throw new BusinessException("企业名称不能为空");
        }
        if(StrUtil.isBlank(paramDto.getLinkMan())) {
            throw new BusinessException("联系人不能为空");
        }
        if(StrUtil.isBlank(paramDto.getLinkPhone())) {
            throw new BusinessException("联系电话不能为空");
        }
    }

}
